package com.ubtechinc.cruzr.libai.honglauncher.http;

import android.util.Log;


import com.ubtechinc.cruzr.libai.honglauncher.BuildConfig;
import com.ubtechinc.cruzr.libai.honglauncher.Constants;
import com.ubtrobot.retrofit.adapter.urest.URestCallAdapterFactory;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

public class HttpManager {
    private volatile static HttpManager instance;
    private static ApiService apiService;
    private HttpManager() {
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("httpLog", message);
            }
        });
        loggingInterceptor.setLevel(level);

        //OkHttpClient初始化
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new HttpSignInterceptor(BuildConfig.APP_ID, BuildConfig.APP_KEY))
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(client)
                //配置URest Adapter
                .addCallAdapterFactory(URestCallAdapterFactory.create())
                .addConverterFactory(FastJsonConverterFactory.create())
                .build();

        apiService =retrofit.create(ApiService.class);
    }

    public static HttpManager getInstance() {
        if (instance == null) {
            synchronized (HttpManager.class) {
                if (instance == null) {
                    instance = new HttpManager();
                }
            }
        }
        return instance;
    }

    /**
     * 获取全局的网络请求服务
     *
     * @return apiService
     */
    public ApiService getApiService() {
        return apiService;
    }
}
